#### Conceptualizing and Measuring Support for Democracy: A New Approach
#### R code to run analyses within each of the national samples

# install packages (if required)
install.packages(
  c("tidyverse", "psych", "lavaan", "car", "devtools", "psychTools", 
    "tth", "haven", "RColorBrewer", "matrixStats", "pewmethods", "lme4",
    "reshape2", "pals", "countrycode", "colorspace", "XML", "haven", 
    "labelled", "rstudioapi"))

# install semTable and pewmethods from github (if required)
library(devtools)
install_github("cran/semTable")
install_github("pewresearch/pewmethods")

# load libraries
library(tidyverse)
library(psych)
library(lavaan)
library(car)
library(psychTools)
library(tth)
library(haven)
library(RColorBrewer)
library(matrixStats)
library(lme4)
library(reshape2)
library(pals)
library(countrycode)
library(colorspace)
library(XML)
library(haven)
library(labelled)
library(semTable)
library(pewmethods)
library(rstudioapi)

# Define the vector of country names
cnts <- c("Argentina", "Brazil", "Britain", "Chile", "Germany", "Greece", "Hungary", "Israel", 
          "Mexico", "Netherlands", "Norway", "Peru", "Poland", "Portugal", "South Africa", 
          "Spain", "Taiwan", "Turkey", "USA")

# Save the current working directory (master folder)
# This requires you to use RStudio
# Alternatively, hard code master_dir as the directory in which this code file 
# is found on your computer
WD <- getActiveDocumentContext()$path 
master_dir <- dirname(WD)

# Loop through the vector of country names
for (country in cnts) {
  # Define the path to the country-specific folder
  country_dir <- file.path(master_dir, country)
  # Set the working directory to the country-specific folder
  setwd(country_dir)
  # Define the script path based on the country name
  script_path <- file.path(country_dir, paste0(country, "_supdem_code_v5.R"))
  # Run the R script
  source(script_path)    
  # Reset the working directory to the master folder
  setwd(master_dir)
}
